<?php

namespace Biz\service\advertisement\apiModule;


use Biz\model\advertisement\MPositionExtend;
use Biz\service\advertisement\AdPositionManagement;
use Biz\service\advertisement\AdUserProfileManagement;
use Doraemon\service\position\ConstInterface;
use Doraemon\service\position\PositionRoute;
use Doraemon\service\statSign\Basic;
use Doraemon\service\statSign\Basic as statSign;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Hhzbeads\Img\ImageType;

class BaseModule implements ConstInterface
{
    const FORMAT_HIT = 'formatHit';

    const EXT_TYPE_FLOW = 1;
    const EXT_TYPE_MOCK = 2;
    const EXT_TYPE_KA = 3;
    const EXT_MAP = [
        self::EXT_TYPE_FLOW => 'Banner',
        self::EXT_TYPE_MOCK => '真假动态(需填广告词)',
        self::EXT_TYPE_KA => '原生内容(无广告词)',
    ];
    const GIF_PLAY_TIMES_DEFAULT = 0;
    const GIF_PLAY_TIMES = [
        0 => '永久播放',
        1 => '每次启动播放1次',
        2 => '每次启动播放2次',
        3 => '每次启动播放3次',
        4 => '每次启动播放4次',
        5 => '每次启动播放5次',
        6 => '每次启动播放6次',
        7 => '每次启动播放7次',
        8 => '每次启动播放8次',
        9 => '每次启动播放9次',
        10 => '每次启动播放10次',
        11 => '每次启动播放11次',
        12 => '每次启动播放12次',
        13 => '每次启动播放13次',
        14 => '每次启动播放14次',
        15 => '每次启动播放15次',
        16 => '每次启动播放16次',
        17 => '每次启动播放17次',
        18 => '每次启动播放18次',
        19 => '每次启动播放19次',
        20 => '每次启动播放20次',
    ];
    public $position_id = 0;
    /**
     * @var AdUserProfileManagement
    */
    public $userProfile = null;
    public $statSign = [];
    public static $statSignFieldMap = [
        'index' => 'pos',
        'config_id' => 'id',
        'url_type' => 'link_type',
        'url' => 'link_url',
    ];
    public static $preview = false;
    /**
     * @var array|mixed
     */
    protected array $position_conf = [];

    public function __construct($position_id = 0, $userProfile = null)
    {
        $this->position_id = $position_id;
        $this->position_conf = AdPositionManagement::getConfById($position_id);
        $this->userProfile = $userProfile;
    }

    public static function preview()
    {
        self::$preview = true;
    }

    public function format($hit, $uid, $userProfileExt, $statSignExt)
    {
        return $hit;
    }

    public function getExtInfo($baseInfo)
    {
        $id = $baseInfo['id'] ?? 0;

        return empty($id) ? [] : MPositionExtend::fetchInfoById($id);
    }

    public function extCheckActive($v, $extInput)
    {
        return true;
    }


    public function extUserProfileFl(): array
    {
        return [];
    }

    /**
     * 设置唯一位置
     * @param mixed $v 配置规则信息
     * @return string
     */
    public function uniquePos($v) : string
    {
        return '';
    }

    public static function addStatSignToLink($linkParams, $statSign)
    {
        if ($linkParams && is_string($linkParams)) {
            $linkParams = json_decode($linkParams, true);
            $linkParams['statSign'] = urlencode(base64_encode($statSign));
        } else {
            if (is_array($linkParams)) {
                $linkParams['statSign'] = urlencode(base64_encode($statSign));
            } else {
                $linkParams = ['statSign' => urlencode(base64_encode($statSign))];
            }
        }
        return $linkParams;
    }

    public function formatHits($hits)
    {
        if (method_exists(static::class, static::FORMAT_HIT)) {
            return call_user_func_array([static::class, static::FORMAT_HIT], [$hits]);
        }
        return $hits;
    }

    /**
     * 默认单banner格式
     * @param $hits
     * @return array
     */
    public static function formatHit($hits)
    {

        $hits = empty($hits) ? [] : $hits[array_rand($hits)];

        return $hits;
    }

    public static function formatCurrent($hits): array
    {
        return empty($hits) ? [] : current($hits);
    }

    /**
     * 默认轮播banner格式
     * @param $hits
     * @return array
     */
    public static function formatCarouselHit($hits)
    {
        return $hits;
    }

    /**
     * 位置分隔格式
     * @param $hits
     * @return array
     */
    public static function formatPosHit($hits)
    {
        $pos = [];
        if (empty($hits)) return $pos;
        foreach ($hits as $v) {
            $pos[$v['pos']][] = $v;
        }
        return array_map(function ($v) {
            return $v[array_rand($v)];
        }, $pos);
    }

    public static function formatHitAllForSearchPreWord($hits): array
    {
        $pos = [];
        $top = [];
        foreach ($hits as $v) {
            if ($v['ext_type'] == 0) {
                $top[$v['pos']][] = $v;
            } else {
                $pos[$v['pos']][$v['ext_type']][] = $v;
            }
        }

        $response = [];
        $topResponse = [];
        foreach ($top as $k => $v) {
            $topResponse[$k] = $v[array_rand($v)];
        }
        foreach ($pos as $k => $v) {
            foreach ($v as $key => $item) {
                $response[$k][$key] = $item[array_rand($item)];
            }
        }

        return ['top' => $topResponse, 'response' => $response];
    }

    /**
     * 位置和扩展分隔格式
     * @param $hits
     * @return array
     */
    public static function formatExtPosHitAll($hits)
    {
        $pos = [];
        foreach ($hits as $v) {
            $pos[$v['ext_type']][$v['pos']][] = $v;
        }

        $response = [];
        foreach ($pos as $k => $v) {
            foreach ($v as $key => $item) {
                $response[$k][$key] = $item[array_rand($item)];
            }
        }

        return $response;
    }

    /**
     * 位置和关键字分隔格式
     * @param $hits
     * @return array
     */
    public static function formatPosHitAll($hits)
    {
        $pos = [];
        foreach ($hits as $v) {
            $pos[$v['pos']][$v['ext']['key_word']][] = $v;
        }

        $response = [];
        foreach ($pos as $k => $v) {
            foreach ($v as $key => $item) {
                $response[$k][$key] = $item[array_rand($item)];
            }
        }

        return $response;
    }

    /**
     * 时间线分隔格式
     * @param $hits
     * @return array
     */
    public static function formatDateSeparateHit($hits)
    {
        $nowDate = date('Y-m-d H:i:s');
        $now = [];
        $next = [];
        foreach ($hits as $v) {
            $nextCheck = $v['start_show_time'] > $nowDate;
            if ($nextCheck) {
                $next[$v['start_show_time']] = $v;
            } else {
                $now[] = $v;
            }
        }
        ksort($next);
        return [
            'now_play' => empty($now) ? null : $now[array_rand($now)],
            'next_play' => empty($next) ? null : current($next),
        ];
    }


    public function generateLink($linkType, $linkParams)
    {
        return LinkFormat::generateSingleLink($linkType, $linkParams);
    }

    public function generateImgUrl($pic, $appType = ImageType::APPTYPE_OP, $imgSize = ImageType::IMAGE_SIZE_OP_ORI): string
    {
        return $pic ? ImgUrl::getUrl($appType, $pic, $imgSize) : '';
    }

    public function statSign($value, $extend = [], $params = [])
    {
        if (!$value) return '';

        $type = $value['position_id'];

        $module = PositionRoute::positionStatSign($type);

        if (!$module) return '';

        $ext = statSign::genStatSign($module, $extend, $params, false);

        if (!$ext) return '';

        if ($ext instanceof Basic) {
            $extParams = $ext->getExtParams();
        } else {
            if (empty($extend)) {
                $extend = [];
                foreach (self::$statSignFieldMap as $field => $v) {
                    if (!empty($value[$v])) $extend[$field] = $value[$v];
                }
                return statSign::genStatSign($module, $extend, $params, false);
            } else {
                return $ext;
            }
        }

        $extendParams = [];
        foreach ($extParams as $field => $v) {
            if (isset(self::$statSignFieldMap[$field]) && isset($value[self::$statSignFieldMap[$field]])) {
                $extendParams[$field] = $value[self::$statSignFieldMap[$field]];
            }
        }
        
        return $ext->setExtend($extendParams)->render();
    }

    public function extListMap($ids)
    {
        return empty($ids) ? [] : MPositionExtend::fetchExtListByIds($ids);
    }

    public function formatAdmListExtInfo(&$v, $map)
    {
        $v['ext'] = $map[$v['id']] ?? [];
    }


}